import { defineStore } from 'pinia'

import { getsubjectlist } from '@/api/question'

export const useStore = defineStore('storeId', {
  state: () => ({
    subjectlist: [],
    userinfo: {
      username: '',
      password: '',
      name: '',
      imgurl: '',
      bind: ''
    },
    home: {
      subject: '历史',
      type: '练习',
      num: 3
    },
    collectlist: null
  }),
  getters: {
    double: state => state.count * 2
  },
  actions: {
    initSubjectlist () {
      if (this.subjectlist.length === 0) {
        getsubjectlist().then(res => {
          const arr = []
          for (let i = 0; i < res.subjectlist.length; i++) {
            arr.push(res.subjectlist[i].subject)
          }
          this.subjectlist = arr
        })
      }
    },
    setcollectitem (item) {
      const arr = JSON.parse(JSON.stringify(this.collectlist)) || []
      let index = -1
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].foldername === item.foldername) {
          index = i
          break
        }
      }
      if (index !== -1) {
        // 删除收藏
        if (item.questionIds.length === 0) {
          arr.splice(index, 1)
        } else {
          arr[index] = item
        }
      } else {
        // 添加收藏夹
        arr.push(item)
      }
      // console.log(arr)
      this.collectlist = arr
    }
  }
})
